from pynput.mouse import Controller, Button
from pynput import keyboard, mouse

import time

click_pos = (3244, 639)

mouse_ctrl = Controller()


# def on_click(x, y, button, pressed):
#     print('{0} at {1}'.format(
#         'Pressed' if pressed else 'Released',
#         (x, y)))
#     if not pressed:
#         # Stop listener
#         return False
    
time.sleep(3)
    
# mouse_ctrl.position = (3244, 639)
# for i in range(1, 180):
#     mouse_ctrl.click(Button.left)
#     time.sleep(0.3)

g_operate = False
def on_move(x, y):
    if x != click_pos[0] or y != click_pos[1]:
        # print("move %s,%s"%(x, y))
        global g_operate
        g_operate = True

def on_click(x, y, button, pressed):
    if x != click_pos[0] or y != click_pos[1]:
        # print("click %s,%s"%(x, y))
        global g_operate
        g_operate = True

def on_scroll(x, y, dx, dy):
    print("scroll %s,%s : %s,%s"%(x, y, dx, dy))
    global g_operate
    g_operate = True

g_stop = False

def on_stop():
    print(u'触发组合键，停掉程序!')
    global g_stop
    g_stop = True

def for_canonical(f):
    print(u"for_canonical")
    return lambda k: f(l.canonical(k))

try:
    hotkey = keyboard.HotKey(keyboard.HotKey.parse('<ctrl>+<alt>+t'), on_activate=on_stop)

    print(u"启动键盘侦听线程")
    l = keyboard.Listener(on_press=for_canonical(hotkey.press), on_release=for_canonical(hotkey.release))
    print(u"侦听快捷键,按 Ctrl + Alt + t 停止程序")
    l.start()

    print(u"启动鼠标侦听线程")
    m = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
    m.start()

    i = 0
    while i < 720:
        i = i + 1

        while g_operate:
            print(u"暂停10秒")
            g_operate = False
            time.sleep(10)

        time.sleep(0.333333)
        print("g_stop:%s, g_operate:%s"%(g_stop, g_operate))
        if g_stop:
            break

        mouse_ctrl.position = click_pos
        mouse_ctrl.click(Button.left)
        
except:
    print("except!")
finally:
    l.stop()
    m.stop()